package com.sso.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sso.bean.bo.Ticket;
import com.sso.bean.entity.User;
import com.sso.dao.AuthticationDao;
import com.sso.service.AuthTicketService;
import com.sso.util.EncryptUtil;

@Service("authService")
public class AuthTicketServiceImpl implements AuthTicketService {
	
	private static final Logger LOG = LoggerFactory.getLogger(AuthTicketServiceImpl.class);
	
	@Resource(name = "authticationDao")
	AuthticationDao authticationDao;

	
	@Override
	public User getUserById(long id) {
		return authticationDao.getUserById(id);
	}
	
    @Override
    public User getUserByUsernameAndPassword(String username, String password) {
    	User user = authticationDao.getUserByUsername(username);
    	if (null == user || EncryptUtil.encryptMD5(password).equals(user.getPassword())) {
    		return null;
    	} 
    	return user;
    }
    
	@Override
	public String createTgc(long userId) {
		String tgc = UUID.randomUUID().toString().replace("-", "");
		authticationDao.updateTgcByUserId(userId, tgc);
		return tgc;
	}
	
	@Override
	public synchronized User validationTicket(String ticket_name) {
		Ticket ticket = AuthTicketFactory.credentials.get(ticket_name);
		AuthTicketFactory.credentials.remove(ticket_name);
		return ticket.getUser();
	}

    public static class AuthTicketFactory {
        
        public static  ConcurrentHashMap<String, Ticket> credentials = new ConcurrentHashMap<String, Ticket>();
        
        //ticket失效时间
        public static final int ticketTimeOut = 1*5;
        
        static {
        	ScheduledExecutorService scheduler =  Executors.newScheduledThreadPool(1);
        	scheduler.scheduleAtFixedRate(new Runnable() {
				
				@Override
				public void run() {
					List<String> ticketKeys = new ArrayList<String>();
					for(Entry<String, Ticket> entry : credentials.entrySet()) {
						if(entry.getValue().getRecoverTime().getTime() < System.currentTimeMillis())
							ticketKeys.add(entry.getKey());
					}
					for(String ticketKey : ticketKeys) {
						credentials.remove(ticketKey);
						LOG.info("ticket [" + ticketKey + "] 过期已删除！");
					}
				}
			},  ticketTimeOut , 1, TimeUnit.MINUTES); //过期时间为5分钟
        }
        
        public static String getTicket(User user) {
            String ticket_name = UUID.randomUUID().toString().replace("-", "");
            Timestamp createTime = new Timestamp(System.currentTimeMillis());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createTime);
            calendar.add(Calendar.MINUTE, ticketTimeOut);
            Timestamp recoverTime = new Timestamp(calendar.getTimeInMillis());
            Ticket ticket = new Ticket(user, createTime, recoverTime);
            credentials.putIfAbsent(ticket_name, ticket);
            return ticket_name;
        }
    }

}
